package com.william.lifetraxer.utils;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DbHandler {
	private final int INSER_USER_FAILED = -1;
	private final int DELETE_USER_FAILED = -2;
	private final int UPDATE_USER_FAILED = -3;
	private final int INSERT_USER_SUCCESS = 1;
	private final int DELETE_USER_SUCCESS = 2;
	private final int UPDATE_USER_SUCCESS = -3;
	
	private DbOpenHelper mDbOpenHelper = null;
	
	public DbHandler(Activity context){
		mDbOpenHelper = new DbOpenHelper(context);
	}
	
	public int insertUser(User user){
		int result = this.INSERT_USER_SUCCESS;
		
		SQLiteDatabase db = this.mDbOpenHelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put(UserDb.UserColumns.USERNAME, user.username);
		values.put(UserDb.UserColumns.USER_ID, user.userid);
		values.put(UserDb.UserColumns.NEW_TRACK_ID, user.newTrackid);
		values.put(UserDb.UserColumns.PHOTO_PATH, user.photoPath);
		
		long insertResult = db.insert(UserDb.TABLE_NAME	, UserDb.UserColumns.USERNAME, values);
		
		if(insertResult<0){
			result = this.INSER_USER_FAILED;
		}
		
		return result;
	}
	
	public int deleteUser(String username){
		int result = this.DELETE_USER_SUCCESS;
		
		SQLiteDatabase db = this.mDbOpenHelper.getWritableDatabase();
		
		String whereClause = UserDb.UserColumns.USERNAME + " = " + "'" + username + "'" ;
		
		int deleteResult = db.delete(UserDb.TABLE_NAME, whereClause, null);
		
		if(deleteResult!=1){
			result = this.DELETE_USER_FAILED;
		}
		
		return result;
	}
	
	public int updateUser(User user){
		int result = this.UPDATE_USER_SUCCESS;
		
		SQLiteDatabase db = this.mDbOpenHelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put(UserDb.UserColumns.USERNAME, user.username);
		values.put(UserDb.UserColumns.USER_ID, user.userid);
		values.put(UserDb.UserColumns.NEW_TRACK_ID, user.newTrackid);
		values.put(UserDb.UserColumns.PHOTO_PATH, user.photoPath);
		
		String whereClause = UserDb.UserColumns.USERNAME + " = " + "'" +user.username + "'";
		
		int updateResult = db.update(UserDb.TABLE_NAME, values, whereClause, null);
		
		if(updateResult!=1){
			result=this.UPDATE_USER_FAILED;
		}
		
		return result;
	}
	
	public Cursor getUsers(){
		Cursor result = null;
		
		SQLiteDatabase db = this.mDbOpenHelper.getWritableDatabase();
		
		result = db.query(UserDb.TABLE_NAME, UserDb.fullColumns, null, null , null , null , UserDb.DEFAULT_SORT_ORDER);
		
		return result;
	}
	
}
